package com.five.api.controller;

import com.five.api.configurations.AlipayConfig;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.five.api.service.UserService;
import com.five.api.service.WalletRecordService;
import com.five.controller.BaseController;
import com.five.entity.WalletRecords;
import com.five.util.CreateUuid;
import com.five.vo.BaseResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Controller
@Api(tags = "钱包支付接口")
@CrossOrigin
public class PayController extends BaseController {

    @Autowired
    private WalletRecordService walletRecordService;

    @Autowired
    private UserService userService;


    @PostMapping(value="/doPay")
    @ResponseBody
    @ApiOperation(value ="获取钱包页面接口")
    public BaseResultVO doPay(WalletRecords walletRecords, HttpServletRequest request) throws Exception {

        System.out.println("================ 钱包信息");
        System.out.println(walletRecords);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                        AlipayConfig.gatewayUrl,
                        AlipayConfig.app_id,
                        AlipayConfig.merchant_private_key, "json",
                        AlipayConfig.charset,
                        AlipayConfig.alipay_public_key,
                        AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        // 订单号
        String walletCode = CreateUuid.getUUID();
        // 订单号+用户id
        String out_trade_no = walletRecords.getUserId() +"/"+ walletCode ;
        System.out.println(out_trade_no);
        //付款金额
        String total_amount = String.valueOf(walletRecords.getMoney());

        String subject= "用户充值";

        String body= "";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 生成未付款的记录信息
        walletRecords.setWalletCode(Long.parseLong(walletCode));
        walletRecords.setPayment(1);
        int i = walletRecordService.insertWalletRecord(walletRecords);
        if (i==1){
            // 返回页面
            return  successResp(alipayClient.pageExecute(alipayRequest).getBody());
        }else {
            return errorResp("请重新提交");
        }
    }
 
 
    @RequestMapping("/payReturn")
    @ResponseBody
    public void payReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
                AlipayConfig.sign_type);
        // ——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("商户订单号---------------------------"+out_trade_no);
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("支付宝交易号---------------------------"+trade_no);
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("交易金额---------------------------"+total_amount);

            // 分割订单号获取，用户id和订单号
            String[] split = out_trade_no.split("/");
            Long userId = Long.parseLong(split[0]);
            Long walletCode = Long.parseLong(split[1]);




//             获取交易金额 ，修改用户信息
            BigDecimal balance = new BigDecimal(total_amount);
            System.out.println("金额："+balance);

            // 修改钱包记录的付款状态 和 用户的余额
            try{
                int i = walletRecordService.updateWalletRecord(walletCode,balance,userId);
            }catch (Exception e){
                e.printStackTrace();
            }
            response.sendRedirect("http://localhost:8080/view_cilent/user/study.html");
            //return "trade_no:" + trade_no + "<br/>out_trade_no:" + out_trade_no + "<br/>total_amount:" + total_amount;
 
 
        } else {
            //return "验签失败";
        }
    }
 
    @RequestMapping("/payNotify")
    @ResponseBody
    public String payNotify(HttpServletRequest request) throws Exception {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
                AlipayConfig.sign_type);
        // ——请在这里编写您的程序（以下代码仅作参考）——
        /*
         * 实际验证过程建议商户务必添加以下校验： 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
         * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）， 3、校验通知中的seller_id（或者seller_email)
         * 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
         * 4、验证app_id是否为该商户本身。
         */
        // 验证成功
        if (signVerified) {
            // 商户订单号
            // String out_trade_no = new
            // String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            // 支付宝交易号
            // String trade_no = new
            // String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            if ("TRADE_FINISHED".equals(trade_status)) {

            } else if ("TRADE_SUCCESS".equals(trade_status)) {

            }
            return "success";
        } else {// 验证失败
            return "fail";
        }
    }
}